package com.xu.tools.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author xuguan
 * @date 2023/2/12
 * @desc 配置Feign过滤器, 解决Feign进行远程调用时丢失请求头问题
 */
@Configuration
public class FeignConfig {

    /**
     * 配置openfeign RequestTemplate, 解决Feign进行远程调用时丢失请求头问题
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 获取请求属性
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null && attributes.getRequest() != null) {
                    HttpServletRequest httpServletRequest = attributes.getRequest();

                    // requestTemplate中添加请求头信息
                    Enumeration<String> enumeration = httpServletRequest.getHeaderNames();
                    if (enumeration != null) {
                        while (enumeration.hasMoreElements()) {
                            String key = enumeration.nextElement();
                            String value = httpServletRequest.getHeader(key);
                            if (StringUtils.hasText(value)) {
                                requestTemplate.header(key, value);
                            }
                        }
                    }
                }
            }
        };
    }

    /**
     * 配置openfeign日志级别
     */
    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }
}
